package academic.nantes.teamsync.webservices;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;

import academic.nantes.teamsync.constants.Cst;
import academic.nantes.teamsync.constants.Utils;
import android.util.Log;

public abstract class WebServiceTeamSync {

	// Attributs
	protected String webServiceName;

	protected List<NameValuePair> webServiceParamsBase;

	protected List<NameValuePair> webServiceParams;
	
	protected String result;
	
	protected String resultatWS;
	
	public String getResultatWS() {
		return resultatWS;
	}

	// Analyseur de perfs
	private long startTime;
	
	public static DefaultHttpClient httpclient;
	
	private static HttpPost httppost;
	
	public List<Cookie> cookies;

	public Cookie myCookie;
	
	// Constructeur
	public WebServiceTeamSync(String wsName){
		this.webServiceName = wsName;
		this.webServiceParamsBase =  new ArrayList<NameValuePair>();
		this.webServiceParams =  new ArrayList<NameValuePair>();
		
		this.webServiceParamsBase.add(new BasicNameValuePair("appuser", Cst.WS.APP_USER));
		this.webServiceParamsBase.add(new BasicNameValuePair("apppassword", Cst.WS.APP_PASSWORD));
		
		this.webServiceParamsBase.add(new BasicNameValuePair("v", Long.toString(System.currentTimeMillis())));
		
		httpclient = new DefaultHttpClient();
		
		httppost = new HttpPost(Cst.WS.WS_URL_BASE + this.webServiceName + Cst.WS.WS_URL_EXTENSION);
	}
	
	// Methode
	/**
	 * Execution d'un web service
	 * @return resultat sous forme de chaine de caracteres en JSON fournie par le webservice PHP  
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	protected void executeWebServiceBase() throws ClientProtocolException, IOException{
		InputStream is;
		
		try {
			httppost.setEntity(new UrlEncodedFormEntity(this.webServiceParamsBase));
			String params = "";
			for(NameValuePair p : this.webServiceParams) {
				if (Utils.isNullOrEmpty(params))
					params += "?";
				else
					params += "&";
				params+= p.getName() + "=" + URLEncoder.encode(p.getValue(), "ISO-8859-1");
			}
			httppost.setURI(new URI(httppost.getURI() + params));
			Log.d("WebServiceTeamSync" , httppost.getURI().toString() + " Args : " + new JSONArray(webServiceParams) + "\n" + new UrlEncodedFormEntity(this.webServiceParams).toString());
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			cookies = httpclient.getCookieStore().getCookies();
			is = entity.getContent();

			if(is!=null){

				BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				this.result=sb.toString();
				
			}
			else{
				this.result = "no result";
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			Log.e("webserviceteamsync", "Error catched in WebService Base Call " + e.toString());
		} catch (ClientProtocolException protocoleE ){
			Log.e("webserviceteamsync", "Error catched in WebService Base Call " + protocoleE.toString());
		} catch (IOException  ioE) {
			Log.e("webserviceteamsync", "Error catched in WebService Base Call " + ioE.toString());
		} catch (Exception  generalE) {
			Log.e("webserviceteamsync", "Error catched in WebService Base Call ");
			Log.d("error msg", generalE.getMessage());
			Log.d("stack", generalE.getStackTrace().toString());
			Log.d("class", generalE.getClass().toString());
			Log.d("localizedmsg", generalE.getLocalizedMessage().toString());
			Log.d("cause", generalE.getCause().toString());
			Log.d("tostring", generalE.toString());
		}
		
	}
	
	protected void beforeExec(){
		startTime = new Date().getTime();
	}
	
	protected void afterExec(){
		Log.d("webserviceteamsync_afterexec", "WebService Execution Time : \n"
				+ "Name : " + webServiceName + " duration " + (new Date().getTime() - startTime) + "ms\n"
				+ "Args : " + new JSONArray(webServiceParams) + "\n"
				+ "Result : " + result);
	}
	
}
